import configs from "@/common/config.js"
class Request {
	constructor() {
		// 默认配置
		this.config = {
			baseUrl: configs.baseUrl + '/api',
			header: {
				'content-type': 'application/json',
				"X-Requested-With": "XMLHttpRequest",
				'Access-token':uni.getStorageSync('token')
			},
			url: '',
			data: {},
			params: {},
			method: 'GET',
			dataType: 'json'
		}

		/* 拦截器 */
		this.interceptor = {
			request: cb => {
				if (cb) {
					this.requestBefore = cb
				} else {
					this.requestBefore = request => request
				}
			},
			response: (cb) => {
				if (cb) {
					this.requestAfter = cb
				} else {
					this.requestAfter = response => response
				}
			}
		}
	}


	/* 请求前 */
	static requestBefore(config) {
		return config
	}

	/* 请求后 */
	static requestAfter(response) {
		return response
	}

	/*设置全局配置*/
	setConfig(func) {
		return func(this.config)
	}


	async request(options = {}) {

		options = {
			...options,
			...this.config,
			...this.requestBefore(options)
		}
		return new Promise((resolve, reject) => {
			options.url = options.baseUrl + options.url
			
			options.success = res => {
				resolve(this.requestAfter(res.data))
			}
			options.fail = err => {
				reject(this.requestAfter(err))
			}
			uni.request(options)
		})
	}

	get(url, data,options = {}) {
		return this.request({
			url,
			data,
			method: 'GET',
			...options
		})
	}

	post(url, data, options = {}) {
		return this.request({
			url,
			data,
			method: 'POST',
			...options
		})
	}

}

/**
 *
 */
var request = new Request()

request.interceptor.request((config, cancel) => {
	let token;
	if(uni.getStorageSync('token') ){
		 token = uni.getStorageSync('token')
	} else if(config.custom && config.custom.token){
		 token = config.custom.token
	}
	
	token && request.setConfig(config => {
		config.header.token = token
	})
	return config
});

/* 请求之后拦截器 */
request.interceptor.response((response, config) => {
	if (response.code == 401) {
		uni.removeStorageSync('token')
		uni.showToast({
			title:response.msg,
			icon:'none'
		})
		setTimeout(()=>{
			uni.$u.route({
				url: configs.login
			})
		},500)
	}
	if (response.status == 500) {
		uni.showToast({
			title: response.message,
			icon: 'none',
			duration: 5000,
			mask: true
		});
	}
	if(response.status == 200){
		return response
	} else {
		return Promise.reject(response)
	}
	
})
export default request
